package google.architecture.coremodel.viewmodel;

import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;



import google.architecture.coremodel.R;
import google.architecture.coremodel.constant.ErrorCode;
import google.architecture.coremodel.datamodel.http.entities.OrderData;
import google.architecture.coremodel.datamodel.http.repository.AutoVenderDataRepository;
import google.architecture.coremodel.helper.AppConfigHelper;
import google.architecture.coremodel.navigator.PaymentNavigator;
import google.architecture.coremodel.util.QRCodeUtils;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 保存生命周期和UI所使用的数据
 * Created by dxx on 2017/11/10.
 */

public class PaymentViewModel extends AndroidViewModel {
    protected String TAG = this.getClass().getName();
    protected Context mContext;
    protected AppConfigHelper mAppConfigHelper;

    public PaymentViewModel(@NonNull Application application) {
        super(application);
        mContext = application;
        mAutoVenderDataRepository = new AutoVenderDataRepository(mContext);
        mAppConfigHelper=new AppConfigHelper(mContext);
    }

    protected AutoVenderDataRepository mAutoVenderDataRepository;
    protected PaymentNavigator mNavigator;
    protected final CompositeDisposable mDisposable = new CompositeDisposable();


    public void clearShoppingCart() {
        mAutoVenderDataRepository.clearShoppingCart()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean s) {
                        mAppConfigHelper.saveHasData(false);
                        mNavigator.onClearAllData(true);
                    }
                });

    }

    public void creatTrade(String terNo, int paymentType, String drugInfos) {
        if (mNavigator != null)
            mNavigator.showLoading();
        mAutoVenderDataRepository.creatTrade(terNo, paymentType, drugInfos)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OrderData>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable.add(d);
                    }

                    @Override
                    public void onNext(OrderData value) {
                        if (value.getCode() == 200) {
                            OrderData.Order order = value.getData();
                            if (order != null && !TextUtils.isEmpty(order.getUrl())) {
                                createQRCode(order.getUrl(), paymentType);
                            } else {
                                Log.e(TAG, "订单生成失败！");
                                mNavigator.showError(ErrorCode.FAILED_CREATE_ORDER, "订单生成失败！");
                            }
                        } else {
                            Log.e(TAG, "服务器返回错误信息：code：" + value.getCode() + ",message:" + value.getMessage());
                            mNavigator.showError(ErrorCode.FAILED_CREATE_ORDER, "订单生成失败！");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (mNavigator != null)
                            mNavigator.hideLoading();
                        Log.e(TAG, "onError------>" + e.getMessage());
                        if (mNavigator != null)
                            mNavigator.showError(ErrorCode.FAILED_CREATE_ORDER, mContext.getString(R.string.network_error));
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        Log.i(TAG, "onComplete------>");
                    }
                });
    }

    public void createQRCode(String url, int paymentType) {
        Observable.create(new ObservableOnSubscribe<Bitmap>() {
            @Override
            public void subscribe(ObservableEmitter<Bitmap> emitter) throws Exception {
                Bitmap logoBitmap = null;
                if (paymentType == 1) {
                    logoBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.logo_alipay);
                } else if (paymentType == 2) {
                    logoBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.logo_wxpay);
                }
                Bitmap bitmap = QRCodeUtils.createQRImage(url, 300, 300, logoBitmap);
                emitter.onNext(bitmap);
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Bitmap>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable.add(d);
                    }

                    @Override
                    public void onNext(Bitmap bitmap) {
                        if (mNavigator != null)
                            mNavigator.showImage(bitmap);
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (mNavigator != null)
                            mNavigator.hideLoading();
                        Log.e(TAG, "onError------>" + e.getMessage());
                        if (mNavigator != null)
                            mNavigator.showError(ErrorCode.FAILED_CREATE_QRCODE, "二维码生成失败！");
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        if (mNavigator != null)
                            mNavigator.hideLoading();
                        Log.i(TAG, "onComplete------>");
                    }
                });
    }




    public void setNavigator(PaymentNavigator navigator) {
        mNavigator = navigator;
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        mDisposable.clear();
    }
}
